# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'Cc3h9I4iRK': {  # dwc 密商 原生支付宝
        'API_KEY': 'mOGvV2W8VBWEnkepmHc5k5nkf55o6Bnq',
        'gateway': 'http://p.showsung.com/api/online/payJson',
        'query_gateway': 'http://p.showsung.com/api/query/{}/{}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# orderNo + totalFee + notifyUrl + orderTime + timeStamp + secretKey
def generate_sign(d, key):
    s = d['orderNo'] + str(d['totalFee']) + d['notifyUrl'] + d['orderTime'] + d['timeStamp'] + key
    _LOGGER.info("mishang_nativepay sign str: %s", s)
    return _gen_sign(s)


# out_trade_no + total_fee +notifyUrl+ orderTime + cas_time_stamp + secretKey
def generate_notify_sign(d, key):
    s = d['out_trade_no'] + str(d['total_fee']) + d['notifyUrl'] + d['orderTime'] + d['cas_time_stamp'] + key
    _LOGGER.info("mishang_nativepay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("mishang_nativepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 必填。支付宝：1；微信:2; QQ钱包:3。
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '2'
    elif service == 'alipay':
        payType = '1'
    elif service == 'qq':
        payType = '3'
    else:
        payType = '1'
    return payType


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('secretKey', api_key),
        ('channelId', app_id),
        ('goodsName', 'CH' + local_now().strftime('%Y%m%d%H%M%S')),
        ('totalFee', int(pay_amount * 100)),
        ('orderNo', str(pay.id)),
        (
            'notifyUrl',
            '{}/pay/api/{}/mishang_nativepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('returnUrl',
         '{}/pay/api/{}/mishang_nativepay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('orderTime', local_now().strftime('%Y%m%d%H%M%S')),
        ('timeStamp', str(int(time.time()))),
        ('payCategory', '12'),
        ('payType', _get_pay_type(service)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("mishang_nativepay create  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("mishang_nativepay create rdp data: %s", response.text)
    return {
        'charge_info': json.loads(response.text)['data'].replace('HTTPS://QR.ALIPAY.COM/', 'https://qr.alipay.com/')}


# 1
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("mishang_nativepay notify data: %s", data)
    data['MerchantId'] = app_id
    data['notifyUrl'] = '{}/pay/api/{}/mishang_nativepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH,
                                                                    app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('mishang_nativepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['status']
    trade_no = data['serial_number']
    total_fee = float(data['total_fee']) / 100.0
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '200':
        _LOGGER.info('mishang_nativepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    response = requests.get(_get_query_gateway(app_id).format(app_id, pay_id), timeout=5)
    _LOGGER.info(u'mishang_nativepay query: %s', response.text)
    data = json.loads(response.text)['order']
    if response.status_code == 200:
        trade_status = int(data['payStatus'])  # 2 订单成功
        total_fee = float(data['orderFee'])
        trade_no = ''
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 1：代表未支付；2：代表已支付
        if trade_status == 2:
            _LOGGER.info('mishang_nativepay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('mishang_nativepay data error, status_code: %s', response.status_code)
